import axios from 'axios';

const BASE_URL = 'https://api.deepseek.com/v1'; // DeepSeek API 地址

export async function getChatStream(messages) {
    const API_KEY = localStorage.getItem('deepseekApiKey'); // 从 localStorage 读取 API Key

    if (!API_KEY) {
        throw new Error('请先设置 DeepSeek API Key！');
    }

    const response = await fetch(`${BASE_URL}/chat/completions`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${API_KEY}`,
        },
        body: JSON.stringify({
            model: 'deepseek-chat',
            messages,
            stream: true, // 开启流式返回
        }),
    });

    if (!response.ok || !response.body) {
        throw new Error('Failed to fetch response');
    }

    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let buffer = '';

    return {
        async *[Symbol.asyncIterator]() {
            while (true) {
                const { done, value } = await reader.read();
                if (done) break;

                // 解码 chunk 并添加到缓冲区
                buffer += decoder.decode(value, { stream: true });

                // 解析多行数据
                const lines = buffer.split('\n');
                buffer = lines.pop(); // 可能是半截数据，留待下次解析

                for (const line of lines) {
                    if (line.startsWith('data: [DONE]')) return; // 结束标志

                    try {
                        const json = JSON.parse(line.replace(/^data:\s*/, ''));
                        const content = json.choices?.[0]?.delta?.content || '';

                        if (content) yield content;
                    } catch (err) {
                        console.error('解析流数据出错:', err);
                    }
                }
            }
        }
    };
}
